package src.linkeLlist;

public class no160 {
    //找出两个链表相交的结点

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode p = headA, q = headB;
        //先求链表长度，让长链表的指针先走
        int lengthA = 0, lengthB = 0;
        while (p != null) {
            p = p.next;
            lengthA++;
        }
        while (q != null) {
            q = q.next;
            lengthB++;
        }
        p = headA;
        q = headB;
        if (lengthA > lengthB) {
            int temp = lengthA - lengthB;
            while (temp > 0) {
                p = p.next;
                temp--;
            }
        } else {
            int temp = lengthB - lengthA;
            while (temp > 0) {
                q = q.next;
                temp--;
            }
        }
        while (p != null && q != null) {
            if (p == q) {
                return p;
            } else {
                p = p.next;
                q = q.next;
            }
        }
        return null;

    }
}
